<?php


namespace App\Models;


use App\Jobs\ImgTask;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Services\Aliyun\Video\VideoServices;

class ImFriendsCircle extends BaseModel
{
    use SoftDeletes;
    protected $table = 'im_friends_circle';


    protected $hidden = ['deleted_at'];

    //发布者信息
    public function user()
    {
        return $this->belongsTo(ImUsers::class, 'user_id', 'id')
            ->select(['id', 'nickname', 'headimg']);
    }

    //点赞用户关联
    public function praise()
    {
        return $this->hasMany(ImFriendsCirclePraise::class, 'fc_id', 'id');
    }

    //朋友圈图片关联
    public function imgs()
    {
        return $this->hasMany(ImFriendsCircleImgs::class, 'fc_id', 'id')->select(['fc_id','id', 'url', 'file_id'])
            ->orderBy('sort', 'asc');
    }

    //朋友圈图片关联
    public function imgsTask()
    {
        return $this->hasMany(ImFriendsCircleImgs::class, 'fc_id', 'id')->select(['fc_id','id', 'url', 'file_id'])
            ->where('file_id', '!=', '')
            ->orderBy('sort', 'asc');
    }

    //评论关联
    public function comments()
    {
        return $this->hasMany(ImFriendsCircleComments::class, 'fc_id', 'id')
            ->select(['fc_id', 'friend_id', 'content', 'to_id', 'pid']);
    }



    /**
     * @desc 发布朋友圈
     * @param array $input 传过来数组对象
     * @param int $userId 用户id
     * @param array $headerList 公共头
     * @return array|int[]
     * @author zhouzhou
     * @time 2021/11/23 14:58
     */
    public function addCircle($input, $userId, $headerList = [])
    {
        $this->content = $input['content'] ?? '';
        $this->type = $input['type'];
        $this->visiable = $input['visiable'];
        $this->longitude = $input['longitude'] ?? '';
        $this->latitude = $input['latitude'] ?? '';
        $this->user_id = $userId;
        $this->device = $headerList['terminal'][0];
        $this->reminds = $input['reminds'] ?? '';
        $this->choose_user = $input['choose_user'] ?? '';
        $this->province_id = $input['province_id'] ?? 0;
        $this->city_id = $input['city_id'] ?? 0;
        $this->area_id = $input['area_id'] ?? 0;
        $this->address = $input['address'] ?? '';

        $fileAIMediaAuditJob = new VideoServices();
        $imSensitiveWord = new  ImSensitiveWord();

        //提交智能文本审核
        if (trim($input['content']))
        {
            $flagWord = $imSensitiveWord->getSensitiveInfo(($input['content']));
            $this->status = empty($flagWord) ? 1 : 2;
            $this->remark = empty($flagWord) ? "" : "敏感文字".$flagWord['msg'];

            // 如果未中im词库敏感词走阿里云审核
            if (empty($flagWord))
            {
                $data = $fileAIMediaAuditJob->submitTextAIMediaAuditJob($input['content']); //$taskId智能检测任务ID(可获取智能检查结果）
                $suggestion = $data['data'][0]['results'][0]['suggestion'];
                if ($suggestion != 'pass')
                {
                    $label = $data['data'][0]['results'][0]['label'];
                    $this->status = 2;
                    $this->remark = ($label == 'politics') ? '涉证' : '涉黄';
                }
            }
        }

        $friendFlag = $this->save();
        if (!$friendFlag)
        {
            return ['code' => 0, 'message' => '发布失败'];
        }

        $picture = $input['picture'] ?? ''; // 图片url

        // 插入图片视频附属表
        if ($picture && $friendFlag)
        {
            $circleImgs = [];
            foreach ($picture as $key =>$val)
            {
                $circleImgs[$key]['fc_id'] = $this->id;
                $circleImgs[$key]['type'] = $input['type'];
                $circleImgs[$key]['created_at'] = time();
                $circleImgs[$key]['url'] = $val;
                $circleImgs[$key]['file_id'] = $fileAIMediaAuditJob->submitAIMediaAuditJob($val,$input['type'] - 1); //type=1提交图片  2视频  $taskId智能检测任务ID(可获取智能检查结果）
            }

            $ImFriendsCircleImgs = new ImFriendsCircleImgs();
            $ImFriendsCircleImgs->insert($circleImgs);

            // if ($this->status != 2)
            // {
                ImgTask::dispatch(['fc_id'=>$this->id]);
            // }
        }

        return ['code' => 0, 'id' => $this->id, 'message' => '发布成功'];
    }

    /**
     * @desc 朋友圈广场列表
     * @param int $userId 当前用户id
     * @param int $limit 每页多少个
     * @param int $offset 从第几个开始
     * @return mixed
     * @author zhouzhou
     * @time 2021/11/26 15:15
     */
    public function circleList($userId = 0, $limit = 10, $offset = 0)
    {
        // 所有可看朋友圈的uids，过滤掉不可看的
        $imUserFriend =new ImUserFriend();
        $userList = $imUserFriend->select('other_uid')->where(['user_id'=>$userId, 'status'=>1, 'circle_status'=>1, 'no_allow_status'=>1])
            ->orderBy('id', 'desc')
            ->get()->toArray();
        $otherUids = array_column($userList, 'other_uid');
        array_unshift($otherUids, $userId);

        // 查询用户所有的点赞列表
        $ImFriendsCirclePraise =new ImFriendsCirclePraise();
        $userCirclePraise = $ImFriendsCirclePraise->getCirclePraiseByuid($userId);
        $userPraiseFcIds = array_column($userCirclePraise, 'fc_id');

        // 查询用户的朋友圈权限
        $imUserWay =new ImUserWay();
        $imUserWay = $imUserWay->getWayCircleByuid($otherUids);
        $imUserWay = array_column($imUserWay, 'firend_circle', 'user_id');
        $list = $this->select('id', 'user_id', 'content', 'type', 'reminds', 'choose_user', 'visiable', 'longitude', 'latitude', 'device', 'created_at', 'like_count', 'comment_count', 'address')->with(['user', 'imgs','province', 'city', 'area'])
            ->where(function($query) use ($otherUids){
                $query->where(['is_del'=>2, 'status'=>1])->whereIn('user_id', $otherUids);
            })->orwhere(function ($query) use ($userId) {
                $query->where('is_del', '=', 2)->where('user_id', '=', $userId);
            })
            ->orderBy('id', 'desc')
            ->limit($limit)
            ->offset($offset)
            ->get();

        foreach ($list as $key =>&$val)
        {
            $val['show'] = 0;
            $val['is_parise'] = in_array($val['id'], $userPraiseFcIds) ? 1 : 0;
            $val['show_flag'] = 0;
            // 根据不同状态show字段展示
            switch (intval($val['visiable']))
            {
                case 1:
                    $val['show'] = 1; // 公开
                    break;
                case 2:
                    if ($val['user_id'] == $userId)
                    {
                        $val['show'] = 1; // 2 私密
                        $val['show_flag'] = 1; // 2 私密
                    }
                    break;
                case 3:
                    $chooseUser = explode(",",$val['choose_user']);
                    if (in_array($userId, $chooseUser))
                    {
                        $val['show'] = 1; // 仅某人可见
                        $val['show_flag'] = 1; // 2 私密
                    }
                    break;
                case 4:
                    $chooseUser = explode(",",$val['choose_user']);
                    if (!in_array($userId, $chooseUser))
                    {
                        $val['show'] = 1; // 不给某人可见，不在这里可以看见
                        $val['show_flag'] = 1; // 2 私密
                    }
                    break;
                default:
                    $val['show'] = 0;
                    break;
            }

            // 朋友圈权限
            $firendCircle = $imUserWay[$val['user_id']] ?? 1;

            // 自己朋友圈 这里判断时间超过30天，180天
            if ($userId == $val['user_id'])
            {
                $val['show'] = 1; // 显示
            }
            else if($firendCircle == 2 )
            {
                $val['show'] = $imUserFriend->showFlagTime($val['show_flag'], $val['created_at'], 180, $val['visiable']);
            }
            else if($firendCircle == 3 )
            {
                $val['show'] = $imUserFriend->showFlagTime($val['show_flag'], $val['created_at'], 30, $val['visiable']);
            }
            else if($firendCircle == 4 )
            {
                // 如果标记可看，但是不在时间内
                $val['show'] = $imUserFriend->showFlagTime($val['show_flag'], $val['created_at'], 3, $val['visiable']);
            }

            if ($val['show'] == 0)
            {
                unset($list[$key]);
            }
        }

        $list = array_values($list->toArray());

        return $list;
    }

    /**
     * @desc 朋友圈详情
     * @param int $userId 当前用户id
     * @param int $limit 每页多少个
     * @param int $offset 从第几个开始
     * @return mixed
     * @author zhouzhou
     * @time 2021/11/26 15:15
     */
    public function circleDetail($input, $userId = 0)
    {
        // 查询用户所有的点赞列表
        $ImFriendsCirclePraise =new ImFriendsCirclePraise();
        $userCirclePraise = $ImFriendsCirclePraise->getCirclePraiseByuid($userId);
        $userPraiseFcIds = array_column($userCirclePraise, 'fc_id');

        $detail = $this->select('id', 'user_id', 'content', 'type', 'reminds', 'choose_user', 'visiable', 'longitude', 'latitude', 'device', 'created_at', 'like_count', 'comment_count')->with(['user', 'imgs', 'praise.user'])->with(['praise' => function($q){
            $q->select('fc_id','friend_id');
            $q->where('status','1');
        }])->where(['is_del'=>2, 'id'=>$input['fc_id']])
            ->orderBy('id', 'desc')
            ->first();

        $detail['is_parise'] = in_array($detail['id'], $userPraiseFcIds) ? 1 : 0;

        return $detail;
    }

    /**
     * @desc 朋友圈主页
     * @param int $userId 当前用户id
     * @param int $otherUid 查看对方的朋友圈列表
     * @param int $limit 每页多少个
     * @param int $offset 从第几个开始
     * @return mixed
     * @author zhouzhou
     * @time 2021/11/26 15:15
     */
    public function userCircleList($userId = 0, $otherUid = 0, $limit = 10, $offset = 0)
    {
        // 查询我和对方的关系
        $imUserFriend = new ImUserFriend();
        $userFriend = $imUserFriend->select('id', 'user_id', 'other_uid', 'circle_status', 'no_allow_status', 'note_name')->where(['user_id' => $userId, 'other_uid' => $otherUid])->first();

        $ohterUser = new User();
        $ohterUser = $ohterUser->select('id', 'user_type', 'nickname', 'im_number', 'phone', 'headimg', 'sex', 'personalized_signature','province_id','city_id', 'area_id', 'address')->with(['province','city'])->find($otherUid);

        // 查询对方的隐私设置，
        $ohterUser->firend_circle = $ohterUser->secrecy()->first()->firend_circle;

        // 对方不给你看，直接返回
        if (!empty($userFriend) && $userFriend['no_allow_status'] == 2 && $userId != $otherUid)
        {
            return ['user'=>$ohterUser];
        }

        $imFriendsCircle = $this->select('id', 'user_id', 'content', 'type', 'reminds','choose_user', 'visiable', 'longitude', 'latitude', 'device', 'created_at', 'like_count', 'comment_count')->with(['user', 'imgs'])
            ->where(['is_del'=>2, 'status'=>1, 'user_id'=>$otherUid])
            ->orderBy('id', 'desc')
            ->limit($limit)
            ->offset($offset)
            ->get();

        foreach ($imFriendsCircle as $key =>&$val)
        {
            $val['show'] = 0;
            $val['show_flag'] = 0;
            // 根据不同状态visiable字段展示，这里没有判断超过半年，3天，下面判断
            switch (intval($val['visiable']))
            {
                case 1:
                    $val['show'] = 1; // 公开
                    break;
                case 2:
                    if ($val['user_id'] == $userId)
                    {
                        $val['show'] = 1; // 2 私密
                        $val['show_flag'] = 1; //  私密标签
                    }
                    break;
                case 3:
                    $chooseUser = explode(",",$val['choose_user']);
                    if (in_array($userId, $chooseUser))
                    {
                        $val['show'] = 1; // 仅某人可见
                        $val['show_flag'] = 1; // 仅某人可见
                    }
                    break;
                case 4:
                    $chooseUser = explode(",",$val['choose_user']);
                    if (!in_array($userId, $chooseUser))
                    {
                        $val['show'] = 1; // 不给某人可见，不在这里可以看见
                        $val['show_flag'] = 1; // 2 私密
                    }
                    break;
                default:
                    $val['show'] = 0;
                    break;
            }


            // 自己朋友圈 这里判断时间超过30天，180天
            if ($userId == $ohterUser->id)
            {
                $val['show'] = 1; // 显示
            }
            else if($ohterUser->firend_circle == 2)
            {
                // 半年内
                $val['show'] = $imUserFriend->showFlagTime($val['show_flag'], $val['created_at'], 180, $val['visiable']);
            }
            else if($ohterUser->firend_circle == 3 )
            {
                // 一个月内
                $val['show'] = $imUserFriend->showFlagTime($val['show_flag'], $val['created_at'], 30, $val['visiable']);
            }
            else if($ohterUser->firend_circle == 4 )
            {
                // 3天内，如果标记可看，但是不在时间内
                $val['show'] = $imUserFriend->showFlagTime($val['show_flag'], $val['created_at'], 3, $val['visiable']);
            }

            if ($val['show'] == 0)
            {
                unset($imFriendsCircle[$key]);
            }
        }

        $imFriendsCircle = array_values($imFriendsCircle->toArray());

        return ['user'=>$ohterUser, 'circle'=>$imFriendsCircle];
    }

    /**
     * @desc 自己的朋友圈主页
     * @param int $userId 当前用户id
     * @param int $otherUid 查看对方的朋友圈列表
     * @param int $limit 每页多少个
     * @param int $offset 从第几个开始
     * @return mixed
     * @author zhouzhou
     * @time 2021/11/26 15:15
     */
    public function myCircleList($userId = 0, $limit = 10, $offset = 0)
    {
        $imFriendsCircle = $this->select('id', 'user_id', 'content', 'type', 'reminds', 'choose_user', 'visiable', 'longitude', 'latitude', 'device', 'created_at', 'like_count', 'comment_count')->with(['user', 'imgs'])
            ->where(['is_del'=>2, 'user_id'=>$userId])
            ->orderBy('id', 'desc')
            ->limit($limit)
            ->offset($offset)
            ->get();

        return ['circle'=>$imFriendsCircle];
    }

    /**
     * @desc 删除朋友圈
     * @param array $input 传过来数组对象
     * @param int $userId 用户id
     * @return array|int[]
     * @author zhouzhou
     * @time 2021/11/23 14:58
     */
    public function delCircle($input, $userId)
    {
        $circle = $this->find($input['id']);
        if (!$circle)
        {
            return ['code' => 1, 'message' => '删除失败'];
        }

        if ($circle['user_id'] != $userId)
        {
            return ['code' => 1, 'message' => '权限错误'];
        }

        $circle->delete();

        return ['code' => 0, 'message' => '删除成功'];
    }

    /**
     * @desc 朋友圈设置私密
     * @param array $input 传过来数组对象
     * @param int $userId 用户id
     * @return array|int[]
     * @author zhouzhou
     * @time 2021/11/23 14:58
     */
    public function setSecrecyCircle($input, $userId)
    {
        $circle = $this->find($input['id']);
        if (!$circle)
        {
            return ['code' => 1, 'message' => '设置失败'];
        }

        if ($circle['user_id'] != $userId)
        {
            return ['code' => 1, 'message' => '设置失败'];
        }

        $circle->visiable = 2;
        $circle->save();

        return ['code' => 0, 'message' => '设置成功'];
    }





}
